<?php
defined('_JEXEC') or die;

require_once JPATH_COMPONENT.'/controller.php';

/**
 * Registration controller class for Users.
 *
 * @package		Joomla.Site
 * @subpackage	com_users
 * @since		1.6
 */
class UsersControllerUser extends UsersController
{
	/**
	 * Method to log in a user.
	 *
	 * @since	1.6
	 */
 	function upload($file_id, $folder="", $types="") {
	if(!isset($_FILES[$file_id]['name'])) return array('','No file specified');

	$file_title = $_FILES[$file_id]['name'];
	//Get file extension
	$ext_arr = split("\.",basename($file_title));
	$ext = strtolower($ext_arr[count($ext_arr)-1]); //Get the last extension

	//Not really uniqe - but for all practical reasons, it is
	$uniqer = substr(md5(uniqid(rand(),1)),0,5);
	$file_name = $file_title;//Get Unique Name

	$all_types = explode(",",strtolower($types));
	if($types) {
		if(!in_array($ext,$all_types))
		{
			$result = "'".$_FILES[$file_id]['name']."' is not a valid file."; //Show error if any.
			return array('',$result);
		}
	}

	//Where the file must be uploaded to
	if($folder) $folder .= '/';//Add a '/' at the end of the folder
	$uploadfile = $folder . $file_name;

	$result = '';
	//Move the file from the stored location to the new location
	if (!move_uploaded_file($_FILES[$file_id]['tmp_name'], $uploadfile)) {
		$result = "Cannot upload the file '".$_FILES[$file_id]['name']."'"; //Show error if any.
		if(!file_exists($folder)) {
			$result .= " : Folder don't exist.";
		} elseif(!is_writable($folder)) {
			$result .= " : Folder not writable.";
		} elseif(!is_writable($uploadfile)) {
			$result .= " : File not writable.";
		}
		$file_name = '';

	} else {
		if(!$_FILES[$file_id]['size']) { //Check if the file is made
			@unlink($uploadfile);//Delete the Empty file
			$file_name = '';
			$result = "Empty file found - please use a valid file."; //Show the error message
		} else {
			chmod($uploadfile,0777);//Make it universally writable.
		}
	}

	return array($file_name,$result);
	}

	public function add_meeting()//called by AJAX
	{
		$app       = JFactory::getApplication();
		$user      = JFactory::getUser();
		$check     = JRequest::getVar('check_to');
		$starttime = JRequest::getVar('add_day') . " " .JRequest::getVar('add_from');
		$tmp=date("Y-m-d H:i",strtotime($starttime));
		if($tmp!=$starttime){
			echo "invalid starttime: $starttime";
			die;
		}
		
		//kiem tra xem co phai la tao thoi gian avaiable cho giao vien
		if($check == "")
			$endtime = JRequest::getVar('add_day') . " " .JRequest::getVar('add_to');
		else
			$endtime = JRequest::getVar('add_day') . " " .JRequest::getVar('to_free',"23:30");
		$tmp=date("Y-m-d H:i",strtotime($endtime));
		if($tmp!=$endtime){
			echo "invalid endtime: $endtime";
			die;
		}

		$id_teacher = JRequest::getVar('id_add_teacher');

		//kiem tra xem co phai la tao thoi gian no avaiable cho giao vien
		$id_student = 0;
		if($check == "")
			$id_student = JRequest::getVar('id_add_user');
		
		$subject = "Available";
		$db         = JFactory::getDbo();
		//kiem tra xem co phai la tao thoi gian no avaiable cho giao vien
		if($check == ""){
			//lay ten user
			$query   = "SELECT * FROM #__users WHERE id=$id_student";
			$db->setQuery($query);
			$subject = $db->loadObject()->name;
		}
		
		////kiem tra xem co phai la tao thoi gian avaiable cho giao vien
		$color=9;
		if($check == "")
			$color=1;
		
			$query = "INSERT INTO #__jqcalendar(Subject,Location,Description,StartTime,EndTime,IsAllDayEvent,Color,RecurringRule,id_teacher,id_student,type)values(
		'$subject','','','$starttime','$endtime',0,'$color','',$id_teacher,$id_student,1
		)";
		//echo '<pre>',print_r($query),'</pre>';die;
		if($check)
		{
			$smonth=date("Y-m-01 00:00:00", $this->mySql2PhpTime($starttime));
			$emonth=date("Y-m-t 23:59:59", $this->mySql2PhpTime($starttime));
			//count to see if meeting times exceed limit
			/*
			$db->setQuery("SELECT count(1) FROM #__jqcalendar
			WHERE type=1
			AND id_student=$id_student
			AND StartTime > '$smonth'
			AND StartTime < '$emonth'");
			$mcount=$db->loadResult();
			//meeting limit
			$db->setQuery("SELECT count FROM #__check_meeting WHERE id_user=$id_student");
			$max = $db->loadResult();
			*/
			//if($max-$mcount > 0){
				$db->setQuery($query);
				$db->query();
			//}else{
				//If additional meeting hasn't been used
			//}
		}
		else{//available time for teacher
			$db->setQuery($query);
			$db->query();
		}
		die;
		//$app->redirect('index.php?option=com_users&view=profile&layout=mycarlendar&id='.$id_teacher.'');
	}
	
	public function insert_calendar()
	{
		$app = JFactory::getApplication();
		$user=JFactory::getUser();
		$starttime=JRequest::getVar('day') . " " .JRequest::getVar('from');
		//echo $starttime ;die();
		$endtime=JRequest::getVar('day') . " " .JRequest::getVar('to_nam');
		$id_teacher=JRequest::getVar('id_teacher');
		$id_student=JRequest::getVar('id_student');
		
		$dbo=JFactory::getDbo();
		$query="insert into #__jqcalendar(Subject,Location,Description,StartTime,EndTime,IsAllDayEvent,Color,RecurringRule,id_teacher,id_student)values(
		'".$_POST[subject]."','ssd','".$_POST[subject]."','".$starttime."','".$endtime."',0,'1','dd',".$id_teacher.",".$id_student."
		)";
		$dbo->setQuery($query);
		$dbo->query();
		$app->redirect('index.php?option=com_users&view=profile&layout=student4&user_id='.$id_student.'');
		
	}
	public function save_month_student()
	{
		$app = JFactory::getApplication();
		//print_r($_POST);die();
		$db=JFactory::getDbo();
		$month=JRequest::getInt('month');
		$id_user=JRequest::getInt('id_user');
		$note=JRequest::getString('note');
		$image=$_FILES['image_student']['name'];
		$informaion= "Weight:".JRequest::getInt('vagt').
		";Waist:".JRequest::getInt('talje').
		";Hip:".JRequest::getInt('hofte').
		";Chest1:".JRequest::getInt('bryst').
		";Chest2:".JRequest::getInt('bryst1');
		
		$this->upload('image_student','images/student/',',jpg,jpeg,gif,png,css,bmp');
		
		if($image){
			//[V] image fix for stupidphone:29/08/2014 6:00 PM
			$flg=1;
			list($w, $h)=getimagesize("images/student/".$image);
			if($w > $h){
				$tmp='.png';
			if(strpos("images/student/".$image, $tmp) === false)//prepare
				$tmp = imagecreatefromjpeg("images/student/".$image);
			else
				{$tmp = imagecreatefrompng("images/student/".$image);$flg=0;}
			
			$exif=exif_read_data("images/student/".$image);
			$exif=$exif['Orientation'];

		//determine what oreientation the image was taken at
		switch($exif){

			case 6: // 90 rotate right

			$tmp1 = imagerotate($tmp, - 90, 0);

			break;

		}
			
			if($flg)//output
				imagejpeg($tmp1, "images/student/".$image);
			else
				imagepng($tmp1, "images/student/".$image);
			
			imagedestroy($tmp);//clean up
			imagedestroy($tmp1);
			}
			//
		}
		
		//echo $query ;die();
		$db->setQuery("SELECT id from #__student_month WHERE id_user=$id_user AND month=$month");
		$res=$db->loadObject();
		if(empty($res))
		{
			$query="INSERT INTO #__student_month(id_user,month,event,note,image)VALUES($id_user,$month,'".$informaion."','".$note."','".$image."')";
			//echo $query ;die();
			$db->setQuery($query);
			$db->query();
		}
		else
		{
			if($image)
				$tmp=", image=".$db->quote($image);
			else
				$tmp="";
		$db->setQuery("UPDATE #__student_month SET
		event=".$db->quote($informaion).$tmp.
		", note= ".$db->quote($note).
		" WHERE id_user=$id_user AND month=$month");
		$db->query();
		}

		$app->redirect(JRoute::_('index.php?option=com_users&view=profile&Itemid=118',false));
	}

	public function save_student_note()
	{
		$app = JFactory::getApplication();
		//print_r($_POST);die();
		$db=JFactory::getDbo();
		$month=JRequest::getInt('month');
		$id_user=JRequest::getInt('id_user');
		$note=JRequest::getString('note');
		
		$db->setQuery("SELECT id from #__student_month WHERE id_user=$id_user AND month=$month");
		$res=$db->loadObject();
		if(empty($res))
		{
			$query="INSERT INTO #__student_month(id_user,month,note)VALUES($id_user,$month,'".$note."')";
			//echo $query ;die();
			$db->setQuery($query);
			$db->query();
		}
		else
		{
			$db->setQuery("UPDATE #__student_month SET
		note= ".$db->quote($note).
		" WHERE id_user=$id_user AND month=$month");
		$db->query();
		}

		$app->redirect(JRoute::_('index.php?option=com_users&view=profile&layout=student_checkplan&user_id='.$id_user, false));
	}

	public function upload_student_file()
	{
		$app = JFactory::getApplication();
		$u = JFactory::getUser();
		$sid=JRequest::getInt('stud');
		$db=JFactory::getDbo();
		
		if($_FILES['stufile']['name'])
			$wat='stufile';
		elseif($_FILES['stufile1']['name'])
			$wat='stufile1';
		elseif($_FILES['stufile2']['name'])
			$wat='stufile2';
		
		$file=empty($_FILES[$wat]) ? "" : $_FILES[$wat];
		
		if(isset($u->groups[5])){
			
			if($file){
				//check if student file not empty
				$db->setQuery("SELECT id,file FROM #__student_month WHERE id_user=$sid LIMIT 1");
				$tmp=$db->loadObject();
				$ext=pathinfo($file['name'], PATHINFO_EXTENSION);
			}
			
			if($wat=='stufile'){//up file 1
				$file=$sid ."_kostprogram.". $ext;
				$p="$file::";
				$idx=0;
			}
			elseif($wat=='stufile1'){//up file 2
				$file=$sid ."_indkob.". $ext;
				$p=":$file:";
				$idx=1;
			}
			elseif($wat=='stufile2'){//up file 3
				$file=$sid .".". $ext;
				$p="::$file";
				$idx=2;
			}
			$_FILES[$wat]['name']=$file;
			if(file_exists("files/$file"))
				unlink("files/$file");
			$this->upload($wat, 'files/', 'xls,xlsx,pdf');
				
			if($tmp){
				$tmp=explode(":",$tmp->file);
				if(count($tmp)<2)
					$tmp=$p;
				else{
					$tmp[$idx]=$file;
					$tmp=implode(":",$tmp);
				}
				
				$db->setQuery("UPDATE #__student_month SET file='$tmp' WHERE id_user=$sid");
			}
			else
				$db->setQuery("INSERT #__student_month(id_user,month,file)VALUES($sid," .date("n"). ",'$file')");
			
			$db->query();
		}

		if($idx==2)
		$app->redirect(JRoute::_("index.php?option=com_users&view=profile",false));
		$app->redirect(JRoute::_("index.php?option=com_users&view=profile&layout=student_checkplan&user_id=$sid",false));
	}

	public function edit_meeting()
	{
		$app = JFactory::getApplication();
		$db=JFactory::getDbo();
		$subject=JRequest::getVar('subject');
		$day=JRequest::getVar('date_meeting');
		$from=$day." ".(JRequest::getVar('from_nam'));
		//echo $from ;die(); 
		$to=$day." ".((JRequest::getVar('to_nam')));
		$id=JRequest::getVar('id_meeting');
		$id_teacher=JRequest::getVar('id_teacher');
		// lay ten user
        $query="select * from #__users a ,#__jqcalendar b where b.id_student=a.id";
        $name=$db->setQuery($query)->loadObject()->name;
        $query="update #__jqcalendar set Subject='".$name."',Description='".$name."',StartTime='".$from."',EndTime='".$to."' where Id=".$id." ";
		$db->setQuery($query);
	    $db->query();
		$app->redirect('index.php?option=com_users&view=profile&layout=mycarlendar&id='.$id_teacher.'');
		//echo "dd";die();
	}
	public function login()
	{
		JSession::checkToken('post') or die('<a href="'.JURI::root().'">'.JText::_('JInvalid_Token').'</a>');

		$app = JFactory::getApplication();

		// Populate the data array:
		$data = array();
		$data['return'] = base64_decode(JRequest::getVar('return', '', 'POST', 'BASE64'));
		$data['username'] = JRequest::getVar('username', '', 'method', 'username');
		$data['password'] = JRequest::getString('password', '', 'post', JREQUEST_ALLOWRAW);

		// Set the return URL if empty.
		if (empty($data['return'])) {
			$data['return'] = 'index.php?option=com_users&view=profile';
		}

		// Set the return URL in the user state to allow modification by plugins
		$app->setUserState('users.login.form.return', $data['return']);

		// Get the log in options.
		$options = array();
		$options['remember'] = JRequest::getBool('remember', false);
		$options['return'] = $data['return'];

		// Get the log in credentials.
		$credentials = array();
		$credentials['username'] = $data['username'];
		$credentials['password'] = $data['password'];

		// Perform the log in.
		if (true === $app->login($credentials, $options)) {
			// Success
			$app->setUserState('users.login.form.data', array());
			//$app->redirect(JRoute::_($app->getUserState('users.login.form.return'), false));
			$u=JFactory::getUser();
			$app->redirect(JRoute::_('index.php?option=com_users&view=profile&Itemid='.($u->groups[5]==5 ? '116' : '118'),false));//[V]either student or teacher
		}else{
			// Login failed !
			$data['remember'] = (int)$options['remember'];
			$app->setUserState('users.login.form.data', $data);
			//$app->redirect(JRoute::_('index.php?option=com_users&view=login', false));
			//$app->redirect('index.php?error=error');
            require_once 'Mobile_Detect.php';
            $detect = new Mobile_Detect;
            if ( $detect->isMobile() ) {
                $app->redirect('index.php?option=com_users&view=login&error=1');
            } else {
			$app->redirect('index.php?error=error');
            }
			
		}
	}

	public function register_device()
	{

		$id_user = JRequest::getInt('id_user');
		// Put your private key's passphrase here:
		$deviceid = JRequest::getVar('device_id');
		$type = JRequest::getVar('type');

		if($type=="ANDROID")
			$isActive="A";
		else
			$isActive="I";

		$db=JFactory::getDbo();
		$db->setQuery("SELECT id FROM #__user_iddevice WHERE id=".$id_user);
		$result=$db->loadResult();
		if($result){
			$db->setQuery("UPDATE #__user_iddevice SET
			id_device=".$db->quote($deviceid).",
			type=".$db->quote($type).",
			isActive=".$db->quote($isActive).
			" WHERE id=$result");
		}else
			$db->setQuery("INSERT INTO #__user_iddevice (id_device,id,isActive,type)
			VALUES(" .$db->quote($deviceid). "," .$id_user. "," .$db->quote($isActive). "," .$db->quote($type). ")");
		$result=$db->query(); 
		if($result)
			$output['status']="OK";
		else
			$output['status']="FALSE"; 
		print(json_encode($output));die();	
	}
//*
	public function getdevices()
	{
		$db=JFactory::getDbo();
		$db->setQuery("SELECT * FROM #__user_iddevice");
		$result=$db->loadObjectList();
		if(!$result)
			$result['status']="FALSE"; 
		echo "<!--pre>",json_encode($result),"<pre-->";die();	
	}
//*/
	public function delete_device()
	{
		$id_user = JRequest::getVar('id_user');
		$db=JFactory::getDbo();
	
		$db->setQuery("UPDATE #__user_iddevice SET
		isActive=''
		,id_device=''
		WHERE id=$id_user");
		$result=$db->query(); 

		if($result)
			$output['status']="OK";
		else
			$output['status']="FALSE"; 
		print(json_encode($output));die();	
	}
	public function login_app()
	{

		$app = JFactory::getApplication();

		// Populate the data array:
		$data = array();
		$data['return'] = base64_decode(JRequest::getVar('return', '', 'POST', 'BASE64'));
		$data['username'] = JRequest::getVar('username', '', 'method', 'username');
		$data['password'] = JRequest::getVar('password', '', 'method', "password");
        //echo  $data['password']; die();
		// Set the return URL if empty.
		if (empty($data['return'])) {
			$data['return'] = 'index.php?option=com_users&view=profile';
		}

		// Set the return URL in the user state to allow modification by plugins
		$app->setUserState('users.login.form.return', $data['return']);

		// Get the log in options.
		$options = array();
		$options['remember'] = JRequest::getBool('remember', false);
		$options['return'] = $data['return'];

		// Get the log in credentials.
		$credentials = array();
		$credentials['username'] = $data['username'];
		$credentials['password'] = $data['password'];

		// Perform the log in.
		if (true === $app->login($credentials, $options)) {
			$dbo=JFactory::getDbo();
			$sql="select id,group_id from #__users a ,#__user_usergroup_map b where a.username='".$data[username]."' and a.id=b.user_id";
			$dbo->setQuery($sql);
			$row=$dbo->loadAssoc();
			$output=$row;
			$output['status']="OK";
			print(json_encode($output));die();
		}else{
		  $output['status']="FALSE";
		  $output['id']="0";
		  $output['group_id']="0";
		  print(json_encode($output));die();
		  
		}

	}
	
	public function get_all_calendar()
	{
		    $dbo=JFactory::getDbo();
			$sql="select * from #__jqcalendar";
			$dbo->setQuery($sql);
			$row=$dbo->loadObjectList();
			$output=$row;
			print(json_encode($output));die();
	}
	
	public function get_all_calendar_teacher()
	{
		    $dbo=JFactory::getDbo();
		    $id=JRequest::getVar('id', '', 'method', 'username');
			$sql="select * from #__jqcalendar where id_teacher=".$id."";
			$dbo->setQuery($sql);
			$row=$dbo->loadObjectList();
			$output=$row;
			print(json_encode($output));die();
	}

	private function mySql2PhpTime($sqlDate){
		$arr = date_parse($sqlDate);
		return mktime($arr["hour"],$arr["minute"],$arr["second"],$arr["month"],$arr["day"],$arr["year"]);
	}

	private function php2MySqlTime($date){
		return date("Y-m-d H:i:00", $date);
	}

	private function colorDB2App($c){
		if($c==10)
			return "8";
		if($c==2)
			return "1";

			return "255";
	}

	private function colorApp2DB($c){
		if($c==8)
			return "10";
		if($c==1)
			return "2";

			return "14";
	}

	public function get_all_calendar_student()
	{

		date_default_timezone_set("Europe/Copenhagen");
			$db=JFactory::getDbo();
			$id=JRequest::getVar('id', '', 'method', 'username');
			$output=array();
			$sql="SELECT * FROM #__jqcalendar WHERE id_student=".$id." AND type=0";
			$db->setQuery($sql);
			$row=$db->loadObjectList();

		$db->setQuery("SELECT registerDate FROM `#__users` WHERE id=$id");
		$res=$db->loadResult();
		$res=$this->mySql2PhpTime($res);
		$monday =  date("d", $res) - date('N', $res) + 1;
		$res = mktime(0,0,0,date("m", $res), $monday, date("Y", $res));//whatever day, goto Monday in current week
			$now=time();

			foreach($row as $v){
				$v->Color+=0;
				//translate from calendar color to app color
				$v->Color=$this->colorDB2App($v->Color);

				$xTime=explode(" ", $v->StartTime);$xTime=trim($xTime[1]);
				$sDate=$this->mySql2PhpTime($v->StartTime);

				if($sDate<=$now)
					$output[]=$v;
//clone records have rules, cloned from datafeed.php
/*
each item
if has rules
	each weeknumber
		RegisterMonday+weeknumber*604800
*/
//*

				if($v->RecurringRule){

					$v->RecurringRule=json_decode($v->RecurringRule);
					foreach($v->RecurringRule->weeks as $vv){

						$week=strtotime(date("Y-m-d H:i", $res) ."+". $vv ." weeks");
						foreach($v->RecurringRule->weekdays as $vvv){

							$sclone=strtotime(date("Y-m-d ".$xTime, $week)."+".($vvv-1)." days");
							if($sclone <= $sDate OR $sclone>$now)
								continue;
$tmp=clone $v;
$tmp->StartTime=$this->php2MySqlTime($sclone);
$tmp->EndTime=$this->php2MySqlTime($sclone+3600);
unset($tmp->RecurringRule);
$tmp->Color=isset($v->RecurringRule->data) ? $v->RecurringRule->data->$vv->$vvv : 14;
$tmp->Color=$this->colorDB2App($tmp->Color);
//$tmp->clone=1;
$output[]=$tmp;
						}
					}
					unset($v->RecurringRule);
				}
				///checking*/
			}

			echo json_encode($output);exit();
	}
	
	private function logToFile($filename, $msg)
	{
		// open file
		$fd = fopen($filename, "a");
		// append date / time to message
		$str= "[" . date("Y-m-d h:i:s") . "] " . $msg;
		// write string
		fwrite($fd, $str . "\n");
		// close file
		fclose($fd);
	}
	
	public function update_calendar()
	{
		$db=JFactory::getDbo();
		$id=JRequest::getInt('id', 0);
		$color=JRequest::getInt('color', '');
		$sTime=str_replace("%20", " ", JRequest::getVar('StartTime', ''));
		date_default_timezone_set("Europe/Copenhagen");
		//translate from app color to calendar color
		$color=$this->colorApp2DB($color);


		$db->setQuery("SELECT * FROM #__jqcalendar WHERE Id=$id");
		$row=$db->loadObject();
		
		if($row->StartTime != $sTime&&$row->RecurringRule){//is clone

			$db->setQuery("SELECT registerDate FROM `#__users` WHERE id=".$row->id_student);
			$regTime=$db->loadResult();$regTime=$this->mySql2PhpTime($regTime);
			$monday =  date("d", $regTime) - date('N', $regTime) + 1;
			$regTime = mktime(0,0,0,date("m", $regTime), $monday, date("Y", $regTime));

			$sTime=$this->mySql2PhpTime($sTime);
			$DOW=(int)date("N", $sTime);
			$monday =  date("d", $sTime) - date('N', $sTime) + 1;
			$sTime = mktime(0,0,0,date("m", $sTime), $monday, date("Y", $sTime));

			$w=floor(($sTime-$regTime)/604800);
			
			$row->RecurringRule=json_decode($row->RecurringRule);
			
			$w=		array_search($w, $row->RecurringRule->weeks);
			$DOW=	array_search($DOW, $row->RecurringRule->weekdays);
			$w=		$row->RecurringRule->weeks[$w];
			$DOW=	$row->RecurringRule->weekdays[$DOW];

			$row->RecurringRule->data->$w->$DOW=$color;
			$row->RecurringRule=json_encode($row->RecurringRule);

			$db->setQuery("UPDATE #__jqcalendar SET RecurringRule='".$row->RecurringRule."' WHERE Id=$id");
		}
		else
			$db->setQuery("UPDATE #__jqcalendar SET Color='$color' WHERE Id=$id");
		$result=$db->query();
		if($result==1)
			$output['status']="OK";
		else
			$output['status']="FALSE";

		print(json_encode($output));die();
	} 
	/**
	 * Method to log out a user.
	 *
	 * @since	1.6
	 */
	public function logout()
	{
		//JSession::checkToken('request') or jexit(JText::_('JInvalid_Token'));

		$app = JFactory::getApplication();

		// Perform the log in.
		$error = $app->logout();

		// Check if the log out succeeded.
		if (!($error instanceof Exception)) {
			// Get the return url from the request and validate that it is internal.
			$return = JRequest::getVar('return', '', 'method', 'base64');
			$return = base64_decode($return);
			if (!JURI::isInternal($return)) {
				$return = '';
			}

			// Redirect the user.
			//echo "dd" ;die();
			//$app->redirect(JRoute::_($return, false));
			$app->redirect('index.php');
			return;
			
		} else {
			$app->redirect(JRoute::_('index.phpzz?option=com_users&view=login', false));
		}
	}

	/**
	 * Method to register a user.
	 *
	 * @since	1.6
	 */
	public function register()
	{
		JSession::checkToken('post') or jexit(JText::_('JINVALID_TOKEN'));

		// Get the form data.
		$data	= JRequest::getVar('user', array(), 'post', 'array');

		// Get the model and validate the data.
		$model	= $this->getModel('Registration', 'UsersModel');
		$return	= $model->validate($data);

		// Check for errors.
		if ($return === false) {
			// Get the validation messages.
			$app	= &JFactory::getApplication();
			$errors	= $model->getErrors();

			// Push up to three validation messages out to the user.
			for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
				if ($errors[$i] instanceof Exception) {
					$app->enqueueMessage($errors[$i]->getMessage(), 'notice');
				} else {
					$app->enqueueMessage($errors[$i], 'notice');
				}
			}

			// Save the data in the session.
			$app->setUserState('users.registration.form.data', $data);

			// Redirect back to the registration form.
			$this->setRedirect('index.php?option=com_users&view=registration');
			return false;
		}

		// Finish the registration.
		$return	= $model->register($data);

		// Check for errors.
		if ($return === false) {
			// Save the data in the session.
			$app->setUserState('users.registration.form.data', $data);

			// Redirect back to the registration form.
			$message = JText::sprintf('COM_USERS_REGISTRATION_SAVE_FAILED', $model->getError());
			$this->setRedirect('index.php?option=com_users&view=registration', $message, 'error');
			return false;
		}

		// Flush the data from the session.
		$app->setUserState('users.registration.form.data', null);

		exit;
	}

	/**
	 * Method to login a user.
	 *
	 * @since	1.6
	 */
	public function remind()
	{
		// Check the request token.
		JSession::checkToken('post') or jexit(JText::_('JINVALID_TOKEN'));

		$app	= JFactory::getApplication();
		$model	= $this->getModel('User', 'UsersModel');
		$data	= JRequest::getVar('jform', array(), 'post', 'array');

		// Submit the username remind request.
		$return	= $model->processRemindRequest($data);

		// Check for a hard error.
		if ($return instanceof Exception) {
			// Get the error message to display.
			if ($app->getCfg('error_reporting')) {
				$message = $return->getMessage();
			} else {
				$message = JText::_('COM_USERS_REMIND_REQUEST_ERROR');
			}

			// Get the route to the next page.
			$itemid = UsersHelperRoute::getRemindRoute();
			$itemid = $itemid !== null ? '&Itemid='.$itemid : '';
			$route	= 'index.php?option=com_users&view=remind'.$itemid;

			// Go back to the complete form.
			$this->setRedirect(JRoute::_($route, false), $message, 'error');
			return false;
		} elseif ($return === false) {
			// Complete failed.
			// Get the route to the next page.
			$itemid = UsersHelperRoute::getRemindRoute();
			$itemid = $itemid !== null ? '&Itemid='.$itemid : '';
			$route	= 'index.php?option=com_users&view=remind'.$itemid;

			// Go back to the complete form.
			$message = JText::sprintf('COM_USERS_REMIND_REQUEST_FAILED', $model->getError());
			$this->setRedirect(JRoute::_($route, false), $message, 'notice');
			return false;
		} else {
			// Complete succeeded.
			// Get the route to the next page.
			$itemid = UsersHelperRoute::getLoginRoute();
			$itemid = $itemid !== null ? '&Itemid='.$itemid : '';
			$route	= 'index.php?option=com_users&view=login'.$itemid;

			// Proceed to the login form.
			$message = JText::_('COM_USERS_REMIND_REQUEST_SUCCESS');
			$this->setRedirect(JRoute::_($route, false), $message);
			return true;
		}
	}

	/**
	 * Method to login a user.
	 *
	 * @since	1.6
	 */
	public function resend()
	{
		// Check for request forgeries
		JSession::checkToken('post') or jexit(JText::_('JINVALID_TOKEN'));
	}
	
	function takenote(){
		JSession::checkToken('post') or jexit(JText::_('JINVALID_TOKEN'));
		$txt	= JRequest::getString('note', '');
		$uid	= JRequest::getVar('uid', '');

		$db =& JFactory::getDBO();
		$db->setQuery("SELECT id FROM #__user_notes WHERE user_id=$uid");
		if($id=$db->loadResult())
			$db->setQuery("UPDATE #__user_notes SET body='".$db->escape($txt)."' WHERE id=$id");
		else
			$db->setQuery("INSERT INTO #__user_notes (user_id,catid,body,state) VALUES($uid,7,'".$db->escape($txt)."',1)");

		if($db->query())
			echo "OK";//$txt;
	}
}